package com.daykw.douyin.task;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.entity.Record;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.douyin.config.NutzDaoConfig;
import com.daykw.douyin.http.HttpBase;
import com.daykw.douyin.utils.SpringContextHolder;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;

public class StarAuthSearchThread extends Thread {

	private static Logger logger = Logger.getLogger(StarAuthSearchThread.class);
	private NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);

	@Override
	public void run() {

		try {

			Record r = dao.fetch("t_star_cate", Cnd.where("status", "=", 0));

			if (r == null) {
				return;
			}

			Map<String, String> headers = new HashMap<String, String>();
			String ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36";
			// String cookie = "gr_user_id=ca46222c-f832-4705-98c3-067e89a47976;
			// grwng_uid=4b512e85-c5d7-4f94-98d5-51cebc54cf45;
			// csrftoken=JmYUA6Y2Q8ywhEEBuvVJNljqbGF8w6dH; tt_webid=6715188712819049988;
			// ccid=690e6934eac86fd6472a6fe25c73f7ae;
			// sso_auth_status=bc5da1fa2cc20f848908f506df50f486;
			// toutiao_sso_user=da5750a2fb4a46bfc4f3313ceb9eb00e;
			// 8632e941eb705978_gr_session_id=fe695201-0d84-424e-ab57-3aaf2b61048f;
			// 8632e941eb705978_gr_session_id_fe695201-0d84-424e-ab57-3aaf2b61048f=true;
			// s_v_web_id=cb119ab82593b9ecb2f4f4b68afcec8e;
			// passport_auth_status=00af47d4f9004a0276c2cf63a1c3c1f1;
			// sso_uid_tt=aaa44c3fd4cd0639268fff8a70ab1bbd;
			// login_flag=de3f5d9e705e87b9cc88a24fa1e80596;
			// sid_tt=fe76cd64828e40086bb7aa7fe31a298c;
			// uid_tt=29ca6e53dd25aad1433e6cdd7d4aa9b4;
			// sessionid=fe76cd64828e40086bb7aa7fe31a298c;
			// star_sessionid=fe76cd64828e40086bb7aa7fe31a298c;
			// sid_guard=\"fe76cd64828e40086bb7aa7fe31a298c|1564470297|15552000|Sun\\054
			// 26-Jan-2020 07:04:57 GMT\"";

			Record c = dao.fetch("t_star_cookie", Cnd.where("id", "=", 1));
			String cookie = c.getString("cookie");
			headers.put("user-agent", ua);
			headers.put("cookie", cookie);
			headers.put("referer", "https://star.toutiao.com/ad");

			headers.put(":authority:", "star.toutiao.com");
			headers.put(":method:", "GET");
			headers.put(":scheme:", "http");

			Long id = r.getLong("id");
			Integer page = r.getInt("page");
			String param = r.getString("tag");

			int maxPage = 1;
			int totalCount = 0;
			int pageSize = 30;
			do {

				String url = "https://star.toutiao.com/v/api/demand/author_list/?page=" + page
						+ "&limit=30&need_detail=true&platform_source=1&task_category=1&order_by=score" + "&" + param;

				try {
					HttpBase http = new HttpBase();
//					String result = http.get(url, headers);
					String result = HttpRequest.get(url).header(Header.USER_AGENT, ua).header(Header.COOKIE, cookie)
							.timeout(60000)// 超时，毫秒
							.execute().body();
					logger.info(result);
					JSONObject json = JSONObject.parseObject(result);

					if (json.getInteger("code") == 0) {
						totalCount = json.getJSONObject("data").getJSONObject("pagination").getIntValue("total_count");

						if (maxPage == 1) {
							if (page < 1)
								page = 1;
							if (pageSize < 0)
								pageSize = 30;
							if (totalCount % pageSize == 0) {
								maxPage = totalCount / pageSize;
							} else {

								if (totalCount <= pageSize) {
									maxPage = 1;
								} else {
									maxPage = (totalCount / pageSize) + 1;
								}

							}

						}

						JSONArray arry = json.getJSONObject("data").getJSONArray("authors");

						for (int i = 0; i < arry.size(); i++) {
							JSONObject j = arry.getJSONObject(i);
							String star_id = j.getString("id");
							String nick_name = j.getString("nick_name");
							String auth_url = "https://star.toutiao.com/ad#/author/douyin/" + star_id
									+ "/?recommend=false";
							try {

								Record auth = new Record();

								auth.put(".table", "t_star_auth_info");
								auth.put("star_id", star_id);
								auth.put("nick_name", nick_name);
								auth.put("url", auth_url);
								auth.put("auth_json", j.toJSONString());
								auth.put("create_time", new Date());
								auth.put("status", 0);
								dao.fastInsert(auth);

							} catch (Exception e) {
								// e.printStackTrace();
							}

						}

						dao.update("t_star_cate", Chain.make("page", page).add("total", totalCount),
								Cnd.where("id", "=", id));

						page++;
						if (page > 100) {
							break;
						}
						int i = NumberUtil.generateRandomNumber(40000, 60000, 1)[0];
						logger.info("#########下载中,page:" + page + "，暂停" + (i / 1000) + "秒");

						Thread.sleep(i);
					} else {
						logger.error("#########下载超时,page:" + page + ",暂停5分钟");
						Thread.sleep(300000);
					}

				} catch (Exception e) {
					dao.update("t_star_cate", Chain.make("status", 3), Cnd.where("id", "=", id));
					logger.error("#########下载异常,page:" + page, e);
					Thread.sleep(300000);
				}

			} while (page <= maxPage);
			dao.update("t_star_cate", Chain.make("status", 2), Cnd.where("id", "=", id));
			logger.info("#########下载完毕,page:" + page);
		} catch (Exception e) {

			logger.error("", e);
		}

	}

}
